/**
 * 定时提醒管理器 - 管理所有的餐饮提醒定时器
 */
class ReminderManager {
  constructor () {
    this.timers = {}
    this.reminders = {}
    this.isActive = false
  }

  /**
   * 初始化提醒系统
   * @param {Function} callback - 触发提醒时的回调函数
   */
  init (callback) {
    this.callback = callback
    this.isActive = true
    console.log('提醒系统已初始化')
  }

  /**
   * 设置餐饮提醒
   * @param {Object} meal - 餐饮对象
   * @param {string} meal.id - 餐饮ID
   * @param {string} meal.mealType - 餐次类型
   * @param {string} meal.reminderTime - 提醒时间 HH:mm
   * @param {boolean} meal.enableReminder - 是否启用提醒
   */
  setReminder (meal) {
    if (!this.isActive || !meal.enableReminder || !meal.reminderTime) {
      return false
    }

    // 清除已存在的定时器
    if (this.timers[meal.id]) {
      this.clearReminder(meal.id)
    }

    const timer = this.scheduleReminder(meal)
    this.timers[meal.id] = timer
    this.reminders[meal.id] = meal

    console.log(`餐饮提醒已设置: ${meal.foodName} - ${meal.reminderTime}`)
    return true
  }

  /**
   * 调度提醒
   * @private
   */
  scheduleReminder (meal) {
    const [hours, minutes] = meal.reminderTime.split(':').map(Number)
    const now = new Date()
    const reminderTime = new Date()
    reminderTime.setHours(hours, minutes, 0, 0)

    // 如果提醒时间已过，设置为明天
    if (reminderTime <= now) {
      reminderTime.setDate(reminderTime.getDate() + 1)
    }

    const delay = reminderTime - now

    // 首次提醒
    const timeoutId = setTimeout(() => {
      this.triggerReminder(meal)

      // 设置24小时循环提醒
      const intervalId = setInterval(() => {
        if (this.reminders[meal.id] && this.reminders[meal.id].enableReminder) {
          this.triggerReminder(meal)
        } else {
          clearInterval(intervalId)
          delete this.timers[meal.id]
        }
      }, 24 * 60 * 60 * 1000)

      this.timers[meal.id] = intervalId
    }, delay)

    return timeoutId
  }

  /**
   * 触发提醒
   * @private
   */
  triggerReminder (meal) {
    if (this.callback && typeof this.callback === 'function') {
      this.callback(meal)
    }
    console.log(`提醒触发: ${meal.foodName}`)
  }

  /**
   * 清除单个提醒
   * @param {string} mealId - 餐饮ID
   */
  clearReminder (mealId) {
    if (this.timers[mealId]) {
      clearTimeout(this.timers[mealId])
      clearInterval(this.timers[mealId])
      delete this.timers[mealId]
      delete this.reminders[mealId]
      console.log(`提醒已清除: ${mealId}`)
      return true
    }
    return false
  }

  /**
   * 清除所有提醒
   */
  clearAllReminders () {
    Object.keys(this.timers).forEach(id => {
      clearTimeout(this.timers[id])
      clearInterval(this.timers[id])
    })
    this.timers = {}
    this.reminders = {}
    console.log('所有提醒已清除')
  }

  /**
   * 批量设置提醒
   * @param {Array} meals - 餐饮数组
   */
  setReminders (meals) {
    meals.forEach(meal => {
      this.setReminder(meal)
    })
    console.log(`已设置 ${meals.length} 个提醒`)
  }

  /**
   * 启用所有提醒
   */
  enableAll () {
    this.isActive = true
    Object.values(this.reminders).forEach(meal => {
      if (meal.enableReminder && meal.reminderTime && !this.timers[meal.id]) {
        this.setReminder(meal)
      }
    })
    console.log('所有提醒已启用')
  }

  /**
   * 禁用所有提醒
   */
  disableAll () {
    this.isActive = false
    this.clearAllReminders()
    console.log('所有提醒已禁用')
  }

  /**
   * 更新提醒
   * @param {string} mealId - 餐饮ID
   * @param {Object} updatedMeal - 更新后的餐饮对象
   */
  updateReminder (mealId, updatedMeal) {
    this.clearReminder(mealId)
    this.setReminder(updatedMeal)
    console.log(`提醒已更新: ${mealId}`)
  }

  /**
   * 获取所有活跃的提醒
   */
  getActiveReminders () {
    return Object.values(this.reminders).filter(meal => meal.enableReminder)
  }

  /**
   * 获取提醒统计
   */
  getStatistics () {
    return {
      total: Object.keys(this.timers).length,
      active: Object.values(this.reminders).filter(m => m.enableReminder).length,
      inactive: Object.values(this.reminders).filter(m => !m.enableReminder).length,
      isActive: this.isActive
    }
  }

  /**
   * 获取下一个提醒时间
   * @param {string} mealId - 餐饮ID
   */
  getNextReminderTime (mealId) {
    const meal = this.reminders[mealId]
    if (!meal || !meal.reminderTime) return null

    const [hours, minutes] = meal.reminderTime.split(':').map(Number)
    const now = new Date()
    const next = new Date()
    next.setHours(hours, minutes, 0, 0)

    if (next <= now) {
      next.setDate(next.getDate() + 1)
    }

    return next
  }
}

// 创建单例实例
const reminderManager = new ReminderManager()

export default reminderManager
